<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Jobs\DeleteStar;
use App\Lib\QiNiuAdapter;
use App\Models\Cookbook;
use App\Models\Merchant;
use App\Models\Star;
use Illuminate\Http\Request;

class CookbookController extends BaseController
{

    public $model = Cookbook::class;
    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $title = $request->input('title');
        $category_id = $request->input('category_id');
        $parent_category_id = $request->input('parent_category_id');
        $contact = $request->input('contact');
        $start_at = $request->input('start_at');
        $end_at = $request->input('end_at');
        $audit_status = $request->input('audit_status', -1);
        $order_by_key = $request->input('order_by_key', 'sort');
        $order_by_value = $request->input('order_by_value', 'desc');
        $is_vip = $request->input('is_vip', -1);
        $is_on = $request->input('is_on', -1);

        $users = Cookbook::title($title)
            ->startAt($start_at)
            ->endAt($end_at)
            ->category($category_id)
            ->with('category')
            ->withCertain('parent_category', ['title'])
            ->withCertain('merchant', ['contact'])
            ->isOn($is_on)->auditStatus($audit_status)->when($is_vip != -1, function ($q)use($is_vip) {
                $q->where('is_vip', '=', $is_vip);
            })->when($contact, function ($q) use($contact){
                $q->whereHas('merchant', function ($query) use($contact){
                    $query->where('contact', 'like',  '%' . $contact . '%');
                });
            })->parentCategory($parent_category_id)->orderBy($order_by_key, $order_by_value)->orderBy("id", "desc")
                ->paginate(\request('per_page', 20));

        return $this->paginate($users);
    }

    public function destroy(Request $request) {
        $this->validate($request, [
            'ids' => 'required'
        ]);
        $ids = $request->input('ids');
        $arr_id = explode(",", $ids);
        foreach ($arr_id as $id) {
            $model = Cookbook::find($id);
            $short_video_url = $model->short_video_url;
            $video_url = $model->video_url;
            if ($model->delete()) {
                if ($short_video_url) {
                    QiNiuAdapter::deleteResource($short_video_url);
                }
                if ($video_url) {
                    QiNiuAdapter::deleteResource($video_url);
                }
                $merchant = Merchant::find ($model->merchant_id);
                if ($merchant->cookbook_num)
                    $merchant->increment('cookbook_num', -1);

                dispatch(new DeleteStar(Star::TYPE_COOKBOOK, $id));
            }
        }
        return $this->success([]);
    }

}

